#!/usr/bin/env python
# Author: Chris Moyer
# Session Tool
commands = """Commands:
    sessions list                         List all sessions
    sessions get <session>                Get all information about <session>
    sessions delete <session>             Delete session <session>
    sessions clear                        Delete all sessions
    sessions trim                         Trim all sessions older then MAX_SESSION_LENGTH

    permissions list                      Get all permissions
    permissions add <user> <permission>   Add <permission> to <user>
    permissions rm <user> <permission>    Remove <permission> from <user>

    users list                            List all Users
    users rm <user>                       Remove <user>
    users add <user>                      Add <user> (prompts for info if using Basic Auth)
"""

usage = "%prog [options] [command]\n" + commands + "If you do not pass a command, %prog will run in Interactive Mode"

# Some Time Definitions
SECOND = 1
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
DAY = 24 * HOUR
WEEK = 7 * DAY

MAX_SESSION_LENGTH = DAY

import time
from datetime import datetime

import sys,os


def list():
    """
    List all the Sessions in this domain
    """
    from marajo.appengine.ext.webapp.session import Session
    sessions = Session.find()
    print "%-50s %-25s %-20s" % ("Session ID", "Start Time", "User")
    for s in sessions:
        vals = {}
        vals['id'] = s.id
        vals['start_time'] =  s.start_time
        if s.has_key("user"):
            vals['user'] = s['user']
        else:
            vals['user'] = None
        print "%(id)-50s %(start_time)-25s %(user)-20s" % vals

def get(sid):
    """
    Get this specific session
    """
    from marajo.appengine.ext.webapp.session import Session
    s = Session.get_by_ids(sid)
    print "----------------------------------------------------------------"
    print "Session                   %s" % sid
    for k in s.keys():
        print "%-25s %s" % (k, s.get(k))
    print "----------------------------------------------------------------"

def delete(sid):
    """
    Delete this specific session
    """
    from marajo.appengine.ext.webapp.session import Session
    s = Session.get_by_ids(sid)
    s.delete()
    print "Deleted session: %s" % sid

def clear():
    """
    Clear out all the sessions
    """
    from marajo.appengine.ext.webapp.session import Session
    print "Purging the Session database"
    sessions = Session.find()
    for s in sessions:
        s.delete()
        print "Deleted session: %s" % s.id
    print "Purge Complete"

def trim():
    """
    Trim the session DB, erasing anything older then
    MAX_SESSION_LENGTH seconds
    """
    from marajo.appengine.ext.webapp.session import Session
    print "Trimming the database"
    print "Deleting all sessions older then %d secionds" % MAX_SESSION_LENGTH
    sessions = Session.find()
    sessions.filter("start_time < ", datetime.fromtimestamp(time.time() - MAX_SESSION_LENGTH))
    for s in sessions:
        s.delete()
        print "Deleted session: %s" % s.id
    print "Trim finished"

def permissions_list():
    """
    List all permissions within a domain
    """
    from marajo.appengine.api.users import User
    print "%-50s %-12s" % ("User", "Permission")
    for user in User.find():
        for group in user.get_auth_groups():
            print "%-50s %-12s" % (user.username, group)

def permissions_add(username, permission):
    """
    Add permission <permission> (auth group) to user <username>
    """
    from marajo.appengine.api.users import User
    for u in User.find(username=username):
        u.add_auth_group(permission)
        print "Added: %s to user: %s(%s)" % (permission, u.username, u.id)

def permissions_rm(username, permission):
    """
    Remove permission <permission> from user <username>
    """
    from marajo.appengine.api.users import User
    for u in User.find(username=username):
        u.remove_auth_group(permission)
        print "Removed: %s from user: %s(%s)" % (permission, u.username, u.id)

def users_list():
    """
    List all users within a domain
    """
    from marajo.appengine.api.users import User
    print "Using domain: %s" % User._manager.db_name
    print "%-50s %-12s %-12s %-12s" % ("User ID", "Username", "nickname", "email")
    for user in User.find():
        print "%-50s %-12s %-12s %-12s" % (user.id, user.username, user.nickname, user.email)

def users_add(username):
    """
    Add user <username>
    Prompts for all other info
    """
    from marajo.appengine.api.users import User
    from getpass import getpass
    pwd = getpass("Password:")
    pwd_verify = getpass("Verify Password:")
    if pwd != pwd_verify:
        print "Passwords do not match"
    else:
        u = User()
        u.username = username
        u.password = pwd
        u.email = raw_input("Email: ").strip()
        u.nickname = raw_input("Nickname: ").strip()
        u.save()

def users_rm(username):
    """
    Remove user <username>
    """
    from marajo.appengine.api.users import User
    q = User.find(username = username)
    for u in q:
        print "Deleting user: %s" % u.id
        u.delete()

def execCommand(args):
    module = args[0]
    import marajo
    if module == "sessions":
        command = args[1]
        if command == "list":
            list()
        elif command == "get":
            get(args[2])
        elif command == "delete":
            delete(args[2])
        elif command == "clear":
            clear()
        elif command == "trim":
            trim()
        else:
            print "Unknown Command: %s" % command
    elif module == "permissions":
        command = args[1]
        if command == "list":
            permissions_list()
        elif command == "rm":
            permissions_rm(args[2], args[3])
        elif command == "add":
            permissions_add(args[2], args[3])
    elif module == "users":
        command = args[1]
        if command == "list":
            users_list()
        elif command == "rm":
            if len(args) < 3:
                print "usage: %s %s <user>" % (module, command)
            else:
                users_rm(args[2])
        elif command == "add":
            if len(args) < 3:
                print "usage: %s %s <user>" % (module, command)
            else:
                users_add(args[2])
    elif module == "help":
        print commands

if __name__ == "__main__":
    from optparse import OptionParser
    import os
    parser = OptionParser(version = "%prog version 2.0", usage = usage)
    parser.add_option("-e", "--environment", help="Environment", dest="env", default="prod")
    (options, args) = parser.parse_args()
    if len(args) > 0:
        os.chdir(args[0])

    sys.path.append(os.path.abspath("."))
    sys.path.append(os.path.abspath("./lib"))

    import marajo
    marajo.set_env(os.getcwd(), options.env)

    if len(args) > 1:
        execCommand(args[1:])
    else:
        print "Starting Interactive mode"
        cmd = ""
        while cmd.lower() != "exit":
            try:
                cmd = raw_input(">>> ").lower()
            except EOFError:
                break
            if cmd == "exit":
                break
            execCommand(cmd.split(" "))
